import 'dart:ui' as ui;
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../models/expense_model.dart';
import '../providers/expense_providers.dart';
import '../themes/expense_theme.dart';
import '../widgets/enhanced_year_picker.dart';
import 'category_management_screen.dart';

/// 记账统计界面
class ExpenseStatisticsScreen extends ConsumerStatefulWidget {
  const ExpenseStatisticsScreen({super.key});

  @override
  ConsumerState<ExpenseStatisticsScreen> createState() =>
      _ExpenseStatisticsScreenState();
}

class _ExpenseStatisticsScreenState
    extends ConsumerState<ExpenseStatisticsScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int _selectedYear = DateTime.now().year;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ExpenseTheme.background,
      appBar: AppBar(
        title: const Text('统计分析'),
        backgroundColor: Colors.transparent,
        foregroundColor: Colors.white,
        elevation: 0,
        flexibleSpace: Container(
          decoration: BoxDecoration(gradient: ExpenseTheme.primaryGradient),
        ),
        actions: [
          Container(
            margin: EdgeInsets.only(right: 8.w),
            child: IconButton(
              icon: Container(
                padding: EdgeInsets.all(8.w),
                decoration: BoxDecoration(
                  color: Colors.white.withValues(alpha: 0.2),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: const Icon(Icons.category, color: Colors.white),
              ),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const CategoryManagementScreen(),
                  ),
                );
              },
            ),
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: Colors.white,
          indicatorWeight: 3,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          labelStyle: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
          unselectedLabelStyle: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w400,
          ),
          tabs: [
            Tab(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.dashboard, size: 18.sp),
                  SizedBox(width: 4.w),
                  const Text('概览'),
                ],
              ),
            ),
            Tab(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.trending_up, size: 18.sp),
                  SizedBox(width: 4.w),
                  const Text('趋势'),
                ],
              ),
            ),
            Tab(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.pie_chart, size: 18.sp),
                  SizedBox(width: 4.w),
                  const Text('分类'),
                ],
              ),
            ),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildOverviewTab(),
          _buildMonthlyTrendTab(),
          _buildCategoryStatsTab(),
        ],
      ),
    );
  }

  /// 构建概览标签页
  Widget _buildOverviewTab() {
    final totalIncome = ref.watch(totalIncomeProvider);
    final totalExpense = ref.watch(totalExpenseProvider);
    final netIncome = ref.watch(netIncomeProvider);
    final currentMonthIncome = ref.watch(currentMonthIncomeProvider);
    final currentMonthExpense = ref.watch(currentMonthExpenseProvider);
    final currentMonthNet = ref.watch(currentMonthNetIncomeProvider);

    return SingleChildScrollView(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 总体统计卡片
          _buildOverviewCard('总体统计', [
            _buildStatItem('总收入', totalIncome, ExpenseTheme.incomeGreen),
            _buildStatItem('总支出', totalExpense, ExpenseTheme.expenseRed),
            _buildStatItem(
              '净收入',
              netIncome,
              netIncome >= 0
                  ? ExpenseTheme.incomeGreen
                  : ExpenseTheme.expenseRed,
            ),
          ]),

          SizedBox(height: 16.h),

          // 当月统计卡片
          _buildOverviewCard('当月统计', [
            _buildStatItem(
              '当月收入',
              currentMonthIncome,
              ExpenseTheme.incomeGreen,
            ),
            _buildStatItem(
              '当月支出',
              currentMonthExpense,
              ExpenseTheme.expenseRed,
            ),
            _buildStatItem(
              '当月净收入',
              currentMonthNet,
              currentMonthNet >= 0
                  ? ExpenseTheme.incomeGreen
                  : ExpenseTheme.expenseRed,
            ),
          ]),

          SizedBox(height: 16.h),

          // 快速统计
          _buildQuickStats(),
        ],
      ),
    );
  }

  /// 构建月度趋势标签页
  Widget _buildMonthlyTrendTab() {
    final monthlyStats = ref.watch(monthlyStatisticsProvider(_selectedYear));

    return Column(
      children: [
        // 年份选择器
        Container(
          padding: EdgeInsets.all(16.w),
          child: Row(
            children: [
              Icon(
                Icons.date_range,
                color: ExpenseTheme.primaryBlue,
                size: 20.sp,
              ),
              SizedBox(width: 8.w),
              Text(
                '统计年份',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                  color: ExpenseTheme.textPrimary,
                ),
              ),
              const Spacer(),
              YearPickerButton(
                selectedYear: _selectedYear,
                onYearChanged: (year) {
                  setState(() {
                    _selectedYear = year;
                  });
                },
                startYear: DateTime.now().year - 10,
                endYear: DateTime.now().year + 5,
                title: '选择统计年份',
              ),
            ],
          ),
        ),

        // 月度图表
        Expanded(
          child: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Column(
              children: [
                _buildMonthlyChart(monthlyStats),
                SizedBox(height: 16.h),
                _buildMonthlyList(monthlyStats),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建分类统计标签页
  Widget _buildCategoryStatsTab() {
    final incomeStats = ref.watch(incomeCategoryStatisticsProvider);
    final expenseStats = ref.watch(expenseCategoryStatisticsProvider);

    return SingleChildScrollView(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 收入分类统计
          _buildCategorySection('收入分类', incomeStats, ExpenseTheme.incomeGreen),

          SizedBox(height: 24.h),

          // 支出分类统计
          _buildCategorySection('支出分类', expenseStats, ExpenseTheme.expenseRed),
        ],
      ),
    );
  }

  /// 构建增强的概览卡片
  Widget _buildOverviewCard(String title, List<Widget> children) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: [
          BoxShadow(
            color: ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
            blurRadius: 15,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(20.w),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
                  ExpenseTheme.lightBlue.withValues(alpha: 0.05),
                ],
              ),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.r),
                topRight: Radius.circular(20.r),
              ),
            ),
            child: Row(
              children: [
                Container(
                  padding: EdgeInsets.all(8.w),
                  decoration: BoxDecoration(
                    color: ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: Icon(
                    Icons.analytics,
                    color: ExpenseTheme.primaryBlue,
                    size: 20.sp,
                  ),
                ),
                SizedBox(width: 12.w),
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    color: ExpenseTheme.textPrimary,
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.all(20.w),
            child: Column(children: children),
          ),
        ],
      ),
    );
  }

  /// 构建增强的统计项目
  Widget _buildStatItem(String label, double amount, Color color) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.05),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: color.withValues(alpha: 0.2), width: 1),
      ),
      child: Row(
        children: [
          Container(
            padding: EdgeInsets.all(8.w),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Icon(_getIconForLabel(label), color: color, size: 20.sp),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  label,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: ExpenseTheme.textSecondary,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  '¥${amount.toStringAsFixed(2)}',
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w700,
                    color: color,
                  ),
                ),
              ],
            ),
          ),
          Icon(
            amount >= 0 ? Icons.trending_up : Icons.trending_down,
            color: color,
            size: 24.sp,
          ),
        ],
      ),
    );
  }

  /// 根据标签获取图标
  IconData _getIconForLabel(String label) {
    if (label.contains('收入')) {
      return Icons.account_balance_wallet;
    } else if (label.contains('支出')) {
      return Icons.shopping_cart;
    } else if (label.contains('净')) {
      return Icons.savings;
    } else {
      return Icons.analytics;
    }
  }

  /// 构建快速统计
  Widget _buildQuickStats() {
    final allExpenses = ref.watch(expenseListProvider);
    final totalRecords = allExpenses.length;
    final incomeRecords = allExpenses
        .where((e) => e.type == ExpenseType.income)
        .length;
    final expenseRecords = allExpenses
        .where((e) => e.type == ExpenseType.expense)
        .length;

    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: ExpenseTheme.cardShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '记录统计',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: ExpenseTheme.textPrimary,
            ),
          ),
          SizedBox(height: 16.h),
          Row(
            children: [
              Expanded(
                child: _buildQuickStatItem(
                  '总记录',
                  totalRecords,
                  ExpenseTheme.primaryBlue,
                ),
              ),
              Expanded(
                child: _buildQuickStatItem(
                  '收入记录',
                  incomeRecords,
                  ExpenseTheme.incomeGreen,
                ),
              ),
              Expanded(
                child: _buildQuickStatItem(
                  '支出记录',
                  expenseRecords,
                  ExpenseTheme.expenseRed,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建快速统计项目
  Widget _buildQuickStatItem(String label, int count, Color color) {
    return Column(
      children: [
        Text(
          count.toString(),
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          label,
          style: TextStyle(fontSize: 14.sp, color: ExpenseTheme.textSecondary),
        ),
      ],
    );
  }

  /// 构建月度折线图
  Widget _buildMonthlyChart(Map<String, double> monthlyStats) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.4,
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: [
          BoxShadow(
            color: ExpenseTheme.primaryBlue.withValues(alpha: 0.1),
            blurRadius: 15,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题和图例
          Row(
            children: [
              Icon(
                Icons.trending_up,
                color: ExpenseTheme.primaryBlue,
                size: 20.sp,
              ),
              SizedBox(width: 8.w),
              Text(
                '月度趋势图',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                  color: ExpenseTheme.textPrimary,
                ),
              ),
              const Spacer(),
              _buildLegend(),
            ],
          ),
          SizedBox(height: 20.h),

          // 折线图
          Expanded(child: _buildLineChart(monthlyStats)),
        ],
      ),
    );
  }

  /// 构建图例
  Widget _buildLegend() {
    return Row(
      children: [
        _buildLegendItem('收入', ExpenseTheme.incomeGreen),
        SizedBox(width: 16.w),
        _buildLegendItem('支出', ExpenseTheme.expenseRed),
      ],
    );
  }

  /// 构建图例项目
  Widget _buildLegendItem(String label, Color color) {
    return Row(
      children: [
        Container(
          width: 12.w,
          height: 3.h,
          decoration: BoxDecoration(
            color: color,
            borderRadius: BorderRadius.circular(2.r),
          ),
        ),
        SizedBox(width: 6.w),
        Text(
          label,
          style: TextStyle(
            fontSize: 12.sp,
            color: ExpenseTheme.textSecondary,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  /// 构建折线图
  Widget _buildLineChart(Map<String, double> monthlyStats) {
    // 准备数据
    final List<double> incomeData = [];
    final List<double> expenseData = [];

    for (int month = 1; month <= 12; month++) {
      incomeData.add(monthlyStats['${month}_income'] ?? 0.0);
      expenseData.add(monthlyStats['${month}_expense'] ?? 0.0);
    }

    // 计算最大值用于缩放
    final maxIncome = incomeData.isNotEmpty
        ? incomeData.reduce((a, b) => a > b ? a : b)
        : 0.0;
    final maxExpense = expenseData.isNotEmpty
        ? expenseData.reduce((a, b) => a > b ? a : b)
        : 0.0;
    final maxValue = maxIncome > maxExpense ? maxIncome : maxExpense;

    if (maxValue == 0) {
      return Center(
        child: Text(
          '暂无数据',
          style: TextStyle(fontSize: 16.sp, color: ExpenseTheme.textSecondary),
        ),
      );
    }

    return CustomPaint(
      size: Size.infinite,
      painter: LineChartPainter(
        incomeData: incomeData,
        expenseData: expenseData,
        maxValue: maxValue,
        incomeColor: ExpenseTheme.incomeGreen,
        expenseColor: ExpenseTheme.expenseRed,
        gridColor: ExpenseTheme.divider,
        textColor: ExpenseTheme.textSecondary,
      ),
    );
  }

  /// 构建月度列表
  Widget _buildMonthlyList(Map<String, double> monthlyStats) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: ExpenseTheme.cardShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '月度详情',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: ExpenseTheme.textPrimary,
            ),
          ),
          SizedBox(height: 12.h),
          ...List.generate(12, (index) {
            final month = index + 1;
            final income = monthlyStats['${month}_income'] ?? 0.0;
            final expense = monthlyStats['${month}_expense'] ?? 0.0;
            final net = monthlyStats['${month}_net'] ?? 0.0;

            if (income == 0 && expense == 0) return const SizedBox.shrink();

            return Padding(
              padding: EdgeInsets.only(bottom: 8.h),
              child: Row(
                children: [
                  SizedBox(
                    width: 40.w,
                    child: Text(
                      '${month}月',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: ExpenseTheme.textSecondary,
                      ),
                    ),
                  ),
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '收入 ¥${income.toStringAsFixed(0)}',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: ExpenseTheme.incomeGreen,
                          ),
                        ),
                        Text(
                          '支出 ¥${expense.toStringAsFixed(0)}',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: ExpenseTheme.expenseRed,
                          ),
                        ),
                        Text(
                          '净收入 ¥${net.toStringAsFixed(0)}',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: net >= 0
                                ? ExpenseTheme.incomeGreen
                                : ExpenseTheme.expenseRed,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }

  /// 构建分类统计部分
  Widget _buildCategorySection(
    String title,
    Map<ExpenseCategory, double> stats,
    Color themeColor,
  ) {
    final sortedEntries = stats.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));

    final totalAmount = stats.values.fold(0.0, (sum, amount) => sum + amount);

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: ExpenseTheme.cardBackground,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: ExpenseTheme.cardShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: ExpenseTheme.textPrimary,
            ),
          ),
          SizedBox(height: 12.h),
          if (sortedEntries.isEmpty)
            Center(
              child: Padding(
                padding: EdgeInsets.all(20.w),
                child: Text(
                  '暂无数据',
                  style: TextStyle(
                    color: ExpenseTheme.textSecondary,
                    fontSize: 14.sp,
                  ),
                ),
              ),
            )
          else
            ...sortedEntries.take(5).map((entry) {
              final category = entry.key;
              final amount = entry.value;
              final percentage = totalAmount > 0
                  ? (amount / totalAmount) * 100
                  : 0.0;

              return Padding(
                padding: EdgeInsets.only(bottom: 8.h),
                child: Row(
                  children: [
                    Text(category.icon, style: TextStyle(fontSize: 16.sp)),
                    SizedBox(width: 8.w),
                    Expanded(
                      child: Text(
                        category.displayName,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: ExpenseTheme.textPrimary,
                        ),
                      ),
                    ),
                    Text(
                      '${percentage.toStringAsFixed(1)}%',
                      style: TextStyle(fontSize: 12.sp, color: themeColor),
                    ),
                    SizedBox(width: 8.w),
                    Text(
                      '¥${amount.toStringAsFixed(0)}',
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                        color: themeColor,
                      ),
                    ),
                  ],
                ),
              );
            }),
        ],
      ),
    );
  }
}

/// 自定义折线图绘制器
class LineChartPainter extends CustomPainter {
  final List<double> incomeData;
  final List<double> expenseData;
  final double maxValue;
  final Color incomeColor;
  final Color expenseColor;
  final Color gridColor;
  final Color textColor;

  LineChartPainter({
    required this.incomeData,
    required this.expenseData,
    required this.maxValue,
    required this.incomeColor,
    required this.expenseColor,
    required this.gridColor,
    required this.textColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..strokeWidth = 2.0
      ..style = PaintingStyle.stroke;

    final gridPaint = Paint()
      ..color = gridColor
      ..strokeWidth = 0.5;

    final pointPaint = Paint()..style = PaintingStyle.fill;

    // 绘制网格线
    _drawGrid(canvas, size, gridPaint);

    // 绘制Y轴标签
    _drawYAxisLabels(canvas, size);

    // 绘制X轴标签
    _drawXAxisLabels(canvas, size);

    // 绘制收入折线
    _drawLine(canvas, size, incomeData, incomeColor, paint, pointPaint);

    // 绘制支出折线
    _drawLine(canvas, size, expenseData, expenseColor, paint, pointPaint);
  }

  void _drawGrid(Canvas canvas, Size size, Paint gridPaint) {
    const padding = 40.0;
    final chartWidth = size.width - padding * 2;
    final chartHeight = size.height - padding * 2;

    // 绘制水平网格线
    for (int i = 0; i <= 5; i++) {
      final y = padding + (chartHeight / 5) * i;
      canvas.drawLine(
        Offset(padding, y),
        Offset(size.width - padding, y),
        gridPaint,
      );
    }

    // 绘制垂直网格线
    for (int i = 0; i <= 12; i++) {
      final x = padding + (chartWidth / 11) * i;
      canvas.drawLine(
        Offset(x, padding),
        Offset(x, size.height - padding),
        gridPaint,
      );
    }
  }

  void _drawYAxisLabels(Canvas canvas, Size size) {
    const padding = 40.0;
    final chartHeight = size.height - padding * 2;

    for (int i = 0; i <= 5; i++) {
      final value = (maxValue / 5) * (5 - i);
      final y = padding + (chartHeight / 5) * i;

      final textPainter = TextPainter(
        text: TextSpan(
          text: value >= 1000
              ? '${(value / 1000).toStringAsFixed(1)}k'
              : value.toStringAsFixed(0),
          style: TextStyle(color: textColor, fontSize: 10),
        ),
        textDirection: ui.TextDirection.ltr,
      );
      textPainter.layout();
      textPainter.paint(canvas, Offset(5, y - textPainter.height / 2));
    }
  }

  void _drawXAxisLabels(Canvas canvas, Size size) {
    const padding = 40.0;
    final chartWidth = size.width - padding * 2;

    for (int i = 0; i < 12; i++) {
      final x = padding + (chartWidth / 11) * i;
      final month = i + 1;

      final textPainter = TextPainter(
        text: TextSpan(
          text: '${month}月',
          style: TextStyle(color: textColor, fontSize: 10),
        ),
        textDirection: ui.TextDirection.ltr,
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset(x - textPainter.width / 2, size.height - 25),
      );
    }
  }

  void _drawLine(
    Canvas canvas,
    Size size,
    List<double> data,
    Color color,
    Paint linePaint,
    Paint pointPaint,
  ) {
    const padding = 40.0;
    final chartWidth = size.width - padding * 2;
    final chartHeight = size.height - padding * 2;

    linePaint.color = color;
    pointPaint.color = color;

    final path = Path();
    final points = <Offset>[];

    for (int i = 0; i < data.length; i++) {
      final x = padding + (chartWidth / 11) * i;
      final y = size.height - padding - (data[i] / maxValue) * chartHeight;

      points.add(Offset(x, y));

      if (i == 0) {
        path.moveTo(x, y);
      } else {
        path.lineTo(x, y);
      }
    }

    // 绘制折线
    canvas.drawPath(path, linePaint);

    // 绘制数据点
    for (final point in points) {
      canvas.drawCircle(point, 3, pointPaint);

      // 绘制数据点的白色边框
      final borderPaint = Paint()
        ..color = Colors.white
        ..style = PaintingStyle.fill;
      canvas.drawCircle(point, 4, borderPaint);
      canvas.drawCircle(point, 3, pointPaint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
